﻿using System;
using System.Diagnostics;
using Metro.Kashikoi.Common.ExceptionHandling;
using Metro.Kashikoi.Common.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace Metro.Kashikoi.Common.Management
{
    /// <summary>
    /// This class provides base class for <c>IServiceManager</c>.
    /// </summary>
    public abstract class ServiceManagerBase : Disposable, IServiceManager
    {
        #region IService Members

        /// <summary>
        /// Gets the service status.
        /// </summary>
        public ServiceStatus ServiceStatus { get; private set; }

        /// <summary>
        /// Initializes this service.
        /// </summary>
        public void Initialize()
        {
            {
                try
                {
                    DoInitialize();
                    ServiceStatus = ServiceStatus.Initialized;
                }
                catch (Exception ex)
                {
                    ServiceStatus = ServiceStatus.Error;
                    ExceptionHandler.Handle(ex, "WrapPolicy");
                }
            }
        }

        /// <summary>
        /// Starts this service.
        /// </summary>
        public void Start()
        {
            try
            {
                DoStart();
                ServiceStatus = ServiceStatus.Started;
                Logger.Write(this.GetType().Name, Category.Business, 0, 1, TraceEventType.Start);
            }
            catch (Exception ex)
            {
                ServiceStatus = ServiceStatus.Error;
                ExceptionHandler.Handle(ex, Policy.StartServer);
            }
        }

        /// <summary>
        /// Stops this service.
        /// </summary>
        public void Stop()
        {
            try
            {
                DoStop();
                ServiceStatus = ServiceStatus.Stoped;
                Logger.Write(this.GetType().Name, Category.Business, 0, 1, TraceEventType.Stop);
            }
            catch (Exception ex)
            {
                ServiceStatus = ServiceStatus.Error;
                ExceptionHandler.Handle(ex, Policy.StopServer);
            }
        }

        /// <summary>
        /// Diagnoses this service.
        /// </summary>
        /// <returns></returns>
        public abstract DiagnoseResult Diagnose();

        #endregion

        #region Abstract Members

        /// <summary>
        /// Does the initialize.
        /// </summary>
        protected abstract void DoInitialize();

        /// <summary>
        /// Does the start.
        /// </summary>
        protected abstract void DoStart();

        /// <summary>
        /// Does the stop.
        /// </summary>
        protected abstract void DoStop(); 

        #endregion
    }
}
